import { observable, makeAutoObservable, computed, action, runInAction } from 'mobx'
class Apple {
    apples = []
    eatApples = []
    saveLoading = false
    constructor() {
        makeAutoObservable(this, {
            apples: observable,
            currentTotalWeight: computed,
            currentTotal: computed,
            saveLoading: observable,
            eatApples: observable,
            eatTotalWeight: computed,
            eatTotal: computed,
            save: action,
            eat: action,
        })
    }
    get currentTotalWeight() {
        if (this.apples.length === 0) {
            return 0
        }
        if (this.apples.length === 1) {
            return this.apples[0].weight
        }
        return this.apples.reduce((total, cur) => {
            if (!isNaN(total)) {
                return Number(total) + Number(cur.weight)
            }
            return Number(total.weight) + Number(cur.weight)
        })

    }
    get currentTotal() {
        return this.apples.length
    }
    get eatTotal() {
        return this.eatApples.length
    }
    get eatTotalWeight() {
        if (this.eatApples.length === 0) {
            return 0
        }
        if (this.eatApples.length === 1) {
            return this.eatApples[0].weight
        }
        return this.eatApples.reduce((total, cur) => {
            if (!isNaN(total)) {
                return Number(total) + Number(cur.weight)
            }
            return Number(total.weight) + Number(cur.weight)
        })
    }
    eat = (apple) => {
        this.apples = this.apples.filter(item => apple.No !== item.No);
        this.eatApples.push(apple);
    }
    save = async (apple) => {
        this.saveLoading = true;
        await new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve([])
            }, 2000);
        });
        runInAction(() => {
            this.apples.push(apple)
            this.saveLoading = false
        })

    }

}
const store = new Apple()
export default store;